from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import MessageUploadSerializer
from common.common import get_first_error
from monitor.models import GroupModel, GroupMembersModel, MessageModel
from .models import TokenModel
import logging


logger = logging.getLogger(__name__)

class CsrfExemptSessionAuthentication(SessionAuthentication):
    def enforce_csrf(self, request):
        return



class UploadView(APIView):
    authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)

    def post(self, request):
        context = dict()
        data = MessageUploadSerializer(data=request.POST)
        if not data.is_valid():  # 验证有效性
            errors = data.errors
            key, value = get_first_error(errors)
            context['error'] = key + ' ' + value[0]
            context['err_code'] = 2002
            return Response(context)
        else:
            context['err_code'] = 0
            data = data.data
            user = TokenModel.objects.get(token=data['token']).user
            group = GroupModel.objects.filter(name=data['group'])#找到需要的组
            if not group.exists():
                context['err_code'] = 4004
                context['error'] = "消息组不存在"
                return Response(context)
            group= group.first()
            querys = GroupMembersModel.objects.filter(user=user,group = group)
            if not querys.exists() or querys.first().upload == False:  #无权限
                context['err_code'] = 4003
                context['error'] = "您没有权限在该组消息上传"
                return Response(context)
            MessageModel.objects.create(content=data['content'],uploader=user,group=group)
            return Response(context)
def gen_token(username):
    import hashlib
    import time
    import random
    s = hashlib.sha256()
    salt = time.strftime("%H%M%S")+str(int(random.random()*10000))
    print(salt)
    s.update((username+salt).encode('utf8'))
    b = s.hexdigest()
    return b
class TokenView(APIView):
    authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)

    def put(self, request):
        context = dict()
        user = request.user
        if user.is_anonymous:
            context['err_code'] = 1001
            context['error'] = "您还未登录"
            return Response(context)
        token = gen_token(user.username)
        obj = TokenModel.objects.filter(user=user)#  object has no attribute 'create_or_update'？
        if obj.exists():
            obj=obj.first()
            obj.token=token
            obj.save()
        else:
            TokenModel.objects.create(user=user, token=token)
        context['err_code']=0
        context['data'] = token
        return Response(context)


